<template>
  <view>
    <nav-bar :page-title="lang.pageTitle"/>
    <view :class="[locale]">
      <!-- باش قىسىم -->
      <view class="center margin-bottom-20">
        <view v-if="currentImages.length > 0" class="margin-top center text-28">
          <view class="radio-10 bg-white ltr photo-count">
            {{ `${currentIndex + 1} / ${currentImages.length}` }}
          </view>
        </view>
      </view>

      <!-- رەسىم تاللاش -->
      <swiper :class="['image-card-box']" @change="onSwiperChange"
              :previous-margin="62" :next-margin="62"
              :current="currentIndex" easing-function="linear">
        <swiper-item v-if="currentImages.length === 0">
          <view class="center add-image-box" @click="showUploadPopup = true">
            <view class="flex-center gap-20 radio-20 center add-photo" hover-class="hover">
              <u-icon name="plus" color="#2BE2A0" size="40"/>
              <view class="common-title">{{ lang.addPhoto }}</view>
            </view>
          </view>
        </swiper-item>

        <swiper-item v-if="currentImages.length > 0" v-for="(photo, index) in currentImages" :key="index"
                     :class="['center']">
          <view :class="['add-image-box',{'horizontal': orientation === 2}]">
            <view class="image-box"
                  :style="{justifyContent: getImagePosition.justifyContent,alignItems: getImagePosition.alignItems }">
              <image
                  class="image" :style="{filter: printColor === 1 ? 'grayscale(1)' : '',transform: getCustomScale }"
                  :src="photo.tempFilePath || photo.path" mode="aspectFit" @click="onEditImage"/>
            </view>
          </view>
        </swiper-item>
      </swiper>

      <view class="rotate-buttons">
        <view class="rotate-btn" @click="rotateImage('left')">
          <u-icon name="arrow-left" size="20"/>
        </view>
        <view class="rotate-btn" @click="rotateImage('right')">
          <u-icon name="arrow-right" size="20"/>
        </view>
      </view>

      <view v-if="currentImages.length > 0" class="padding-lr">
        <!-- 操作按钮 -->
        <view class="flex-center gap-20 default-text action-buttons">
          <view class="center action-btn close" @click="onCloseImage">
            <u-icon name="trash" color="#fff" size="20"/>
            <text>{{ lang.closePhoto }}</text>
          </view>

          <view class="center action-btn edit" @click="onEditImage">
            <u-icon name="edit-pen" color="#fff" size="20"/>
            <text>{{ lang.editPhoto }}</text>
          </view>

          <!-- add image-->
          <view class="center action-btn add" @click="showUploadPopup = true">
            <u-icon name="plus" color="#2BE2A0" size="20"/>
            <text>{{ lang.addPhoto }}</text>
          </view>
        </view>

        <!-- 打印设置 -->
        <view class="print-settings">
          <view class="head-title setting-head">{{ lang.printSettings }}</view>

          <scroll-view scroll-y :style="{height: '18vh'}">
            <!-- 纸类型 -->
            <view class="setting-item">
              <view class="common-title text-color">{{ lang.paperType }}</view>
              <radio-group @change="onPaperTypeChange" v-model="paperSize" class="flex-center gap-30 default-text">
                <!-- A3-->
                <label for="A3" class="flex-center gap-8"> {{ 'A3' }}
                  <!--                  :disabled="!getCanPaper(printer.paper_types_supported, 'A3')"-->
                  <radio id="A3"
                         color="#07c160" value="8" class="transform-nine"/>
                </label>
                <!-- A4-->
                <label for="A4" class="flex-center gap-8"> {{ 'A4' }}
                  <radio id="A4" checked color="#07c160" value="9" class="transform-nine"/>
                </label>
              </radio-group>
            </view>

            <!-- 打印数量 -->
            <view class="setting-item">
              <view class="common-title text-color">{{ lang.printCount }}</view>
              <u-number-box v-model="printCount" :min="1" :max="99" @change="onPrintCountChange"/>
            </view>

            <!-- 单双面 -->
            <view class="setting-item">
              <view class="common-title text-color">{{ lang.double }}</view>
              <radio-group @change="onDoubleChange" v-model="duplex" class="flex-center gap-30 default-text">
                <!-- 双面-->
                <label for="double" class="flex-center gap-8"> {{ lang.selectedDouble['double'] }}
                  <radio id="double" :checked="duplex === 2 || duplex === 3" color="#07c160" value="2"
                         class="transform-nine"
                         :disabled="!(printer.supports_double_side === 1 && currentImages.length >= 2)"/>
                </label>
                <!-- 单面-->
                <label for="single" class="flex-center gap-8"> {{ lang.selectedDouble['single'] }}
                  <radio id="single" checked color="#07c160" value="1" class="transform-nine"/>
                </label>
              </radio-group>
            </view>

            <!-- 双面分类 -->
            <view v-if="duplex >= 2" class="setting-item">
              <view class="common-title text-color">{{ lang.doubleType }}</view>
              <radio-group @change="onDoubleChange" v-model="duplex" class="flex-center text-32 gap-30 default-text">
                <!-- 短边 -->
                <label for="shortEdge" class="flex-center gap-8"> {{ lang.selectedDoubleType['shortEdge'] }}
                  <radio id="shortEdge" :checked="duplex===3" color="#07c160" value="3" class="transform-nine"/>
                </label>
                <!-- 长边-->
                <label for="longEdge" class="flex-center gap-8"> {{ lang.selectedDoubleType['longEdge'] }}
                  <radio id="longEdge" :checked="duplex===2" color="#07c160" value="2" class="transform-nine"/>
                </label>
              </radio-group>
            </view>

            <!-- 彩色 -->
            <view class="setting-item">
              <view class="common-title text-color">{{ lang.color }}</view>
              <radio-group @change="onPrintColorChange" v-model="printColor" class="flex-center gap-30 default-text">
                <!-- color-->
                <label for="color" class="flex-center gap-8"> {{ lang.selectedColor['color'] }}
                  <!--                       :disabled="printer.supports_color !== 1"-->
                  <radio id="color"
                         color="#07c160" value="2" class="transform-nine"/>
                </label>
                <!-- black-->
                <label for="black" class="flex-center gap-8"> {{ lang.selectedColor['black'] }}
                  <radio id="black" checked color="#07c160" value="1" class="transform-nine"/>
                </label>
              </radio-group>
            </view>

            <!-- 打印方向 -->
            <view class="setting-item">
              <view class="common-title text-color">{{ lang.orientation }}</view>
              <radio-group @change="onOrientationChange" v-model="orientation" class="flex-center gap-30 default-text">
                <!-- 横向 -->
                <label for="horizontal" class="flex-center gap-8"> {{ lang.selectedOrientation['horizontal'] }}
                  <radio id="horizontal" color="#07c160" value="2" class="transform-nine"/>
                </label>
                <!-- 竖向-->
                <label for="vertical" class="flex-center gap-8"> {{ lang.selectedOrientation['vertical'] }}
                  <radio id="vertical" checked color="#07c160" value="1" class="transform-nine"/>
                </label>
              </radio-group>
            </view>


            <!--  对齐方式-->
            <view class="setting-item" @click="autoAlignPopup = true">
              <view class="common-title text-color width-50">{{ lang.autoAlign }}</view>
              <view class="flex-center gap-8 default-text">
                <view>{{ lang.selectedAutoAlign[selectedAutoAlign[autoAlignIndex].label] }}</view>
                <u-icon :name="arrowIcon" size="16"/>
              </view>
            </view>

            <!-- 缩放比例-->
            <view class="setting-item" @click="scalePopup = true">
              <view class="common-title text-color width-50">{{ lang.scale }}</view>
              <view class="flex-center gap-8 default-text">
                <view>{{ lang.selectedScale[selectedScale[scaleIndex].label] }}</view>
                <u-icon :name="arrowIcon" size="16"/>
              </view>
            </view>

            <!-- 自动缩放 -->
            <view v-if="selectedScale[scaleIndex].label === 'custom'" class="setting-item">
              <view class="common-title text-color width-50">{{ lang.autoScale }}</view>
              <u-number-box v-model="jpScale" :min="1" :max="200"/>
            </view>

            <!-- 打印质量 -->
            <view class="setting-item" @click="qualityPopup = true">
              <view class="common-title text-color">{{ lang.quality }}</view>
              <view class="flex-center gap-8 default-text">
                <view>{{ lang.selectedQuality[qualities[qualityIndex].label] }}</view>
                <u-icon :name="arrowIcon" size="16"/>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>

      <!-- 对齐方式 selected-->
      <popup :show="autoAlignPopup" position="popup-bottom" @update:show="autoAlignPopup = false">
        <view class="position-popup">
          <view class="popup-header">
            <view>{{ lang.autoAlign }}</view>
            <u-icon name="close" @click="autoAlignPopup = false" size="20"/>
          </view>

          <view class="position-grid">
            <view v-for="(pos, index) in selectedAutoAlign" :key="pos.value" @click="onSelectAutoAlign(index)"
                  :class="['position-item', {'active': autoAlignIndex === index}]"
            >
              <!-- TODO 后期使用icon或只字-->
              <view class="position-icon"/>
              <text>{{ lang.selectedAutoAlign[pos.label] }}</text>
            </view>
          </view>
        </view>
      </popup>

      <!-- 打印质量 popup -->
      <popup :show="qualityPopup" position="popup-bottom" @update:show="qualityPopup = false">
        <view class="popup-header">
          <view>{{ lang.quality }}</view>
          <u-icon name="close" @click="qualityPopup = false" size="20"/>
        </view>
        <scroll-view class="popup-list">
          <view
              v-for="(quality, index) in qualities" :key="index" class="popup-item"
              :class="{'active': qualityIndex === index}" @click="onQualityChange(index)"
          >
            <text>{{ lang.selectedQuality[quality.label] }}</text>
            <u-icon v-if="qualityIndex === index" name="checkmark" color="#07c160" :size="20"/>
          </view>
        </scroll-view>
      </popup>


      <!-- 缩放比例 popup -->
      <popup :show="scalePopup" position="popup-bottom" @update:show="scalePopup = $event">
        <view class="popup-header">
          <text>{{ lang.scale }}</text>
          <u-icon name="close" @click="scalePopup = false" size="20"/>
        </view>

        <scroll-view scroll-y class="popup-list">
          <view
              v-for="(item, index) in selectedScale" :key="item.label" class="popup-item"
              :class="{'active': scaleIndex === index}" @click="onSelectScaleChange(index)"
          >
            <text>{{ lang.selectedScale[item.label] }}</text>
            <u-icon v-if="scaleIndex === index" name="checkmark" color="#07c160" :size="20"/>
          </view>
        </scroll-view>
      </popup>
    </view>

    <pay-card :pay-price="totalPrice" @on-pay="printImagePay"/>
    <!-- selected image popup -->
    <upload-select-popup
        :show-popup="showUploadPopup" @choose-message="chooseMessage" @choose-image="chooseImage"
        @close-popup="showUploadPopup = false"/>

    <!-- rotate Image-->
    <view class="canvas">
      <canvas
          canvas-id="rotateCanvas" id="rotateCanvas" :style="{width: canvasWidth + 'px',height: canvasHeight + 'px'}"/>
    </view>
  </view>
</template>

<script lang="ts">
import NavBar from "@/components/nav-bar/nav-bar.vue";
import UploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import {editImageChange, getCanPaper, getFileExtension} from "@/utils/utils";
import Popup from "@/components/popup/popup.vue";
import {mapState} from "vuex";
import PayCard from "@/components/PayCard/PayCard.vue";
import tips from "@/utils/tips";
import {createOrder, getTaskId} from "@/services/order";
import {uploadImageServer} from "@/services/office";

export default {
  components: {PayCard, Popup, UploadSelectPopup, NavBar},
  data() {
    return {
      showUploadPopup: false,
      currentImages: [
        {tempFilePath: "http://tmp/ghJuAnIvFaQ8782831b405e1a17f216a1fe5320e77ca.jpg"},
        {tempFilePath: "http://tmp/ySdUFNAuz0el916308d5ed93d9351383f3007edf7b00.jpg"},
        {tempFilePath: "http://tmp/6UsaSiJCQkOK8038be8dd8fa77e1220e39a2769c8570.jpg"}
      ], // 照片列表
      currentIndex: 0, // 轮播图当前图片索引

      paperSize: '9', // 纸类型
      printCount: 1,// 打印数量
      duplex: 1,
      printColor: 1, // 颜色
      orientation: 1, // 方向

      canvasWidth: 0,
      canvasHeight: 0,

      autoAlignIndex: 4,
      autoAlignPopup: false,
      // 对齐方式
      selectedAutoAlign: [
        {label: 'z1', value: 'left-top'},
        {label: 'z2', value: 'center-top'},
        {label: 'z3', value: 'right-top'},
        {label: 'z4', value: 'left-center'},
        {label: 'z5', value: 'center-center'},
        {label: 'z6', value: 'right-center'},
        {label: 'z7', value: 'left-bottom'},
        {label: 'z8', value: 'center-bottom'},
        {label: 'z9', value: 'right-bottom'},
      ],

      scalePopup: false,
      scaleIndex: 1,
      selectedScale: [
        {label: 'none'},
        {label: 'fit'},
        {label: 'fitw'},
        {label: 'fith'},
        {label: 'fill'},
        {label: 'cover'},
        {label: 'custom'},
      ],


      qualityPopup: false,
      jpScale: 100,
      qualityIndex: 0,
      qualities: [
        {label: 'default', apiValue: -1},
        {label: 'high', apiValue: -4},
        {label: 'normal', apiValue: -3},
        {label: 'low', apiValue: -2},
      ],
      totalPrice: 0,
    }
  },

  computed: {
    ...mapState(["machine", "printer", "machineOnline"]),
    lang() {
      return this.$t('printImage')
    },
    getImagePosition() {
      const position = this.selectedAutoAlign[this.autoAlignIndex].value;
      const styles = {
        justifyContent: 'center',
        alignItems: 'center'
      };

      switch (position) {
        case 'left-top':
          styles.justifyContent = 'flex-start';
          styles.alignItems = 'flex-start';
          break;
        case 'center-top':
          styles.justifyContent = 'center';
          styles.alignItems = 'flex-start';
          break;
        case 'right-top':
          styles.justifyContent = 'flex-end';
          styles.alignItems = 'flex-start';
          break;
        case 'left-center':
          styles.justifyContent = 'flex-start';
          styles.alignItems = 'center';
          break;
        case 'right-center':
          styles.justifyContent = 'flex-end';
          styles.alignItems = 'center';
          break;
        case 'left-bottom':
          styles.justifyContent = 'flex-start';
          styles.alignItems = 'flex-end';
          break;
        case 'center-bottom':
          styles.justifyContent = 'center';
          styles.alignItems = 'flex-end';
          break;
        case 'right-bottom':
          styles.justifyContent = 'flex-end';
          styles.alignItems = 'flex-end';
          break;
      }
      return styles;
    },
    getImageMode() {
      const scaleType = this.selectedScale[this.scaleIndex].label;
      switch (scaleType) {
        case 'fit':
          return 'aspectFit';
        case 'fitw':
          return 'widthFix';
        case 'fith':
          return 'heightFix';
        case 'fill':
          return 'scaleToFill';
        case 'cover':
          return 'aspectFill';
        case 'custom':
          return 'aspectFit';
        case 'none':
          return 'center';
        default:
          return 'aspectFit';
      }
    },

    getCustomScale() {
      const scaleType = this.selectedScale[this.scaleIndex].label;
      if (scaleType === 'custom') {
        return `scale(${this.jpScale / 100})`;
      }
      return 'scale(1)';
    },
  },
  onLoad(query?: AnyObject) {
    this.currentImages = JSON.parse(decodeURIComponent(query.images))
    this.calculatePrice()
  },
  methods: {
    getCanPaper,
    // 微信里上传
    chooseMessage() {
      uni.chooseMessageFile({
        count: 9,
        type: 'image',
        success: (res) => {
          console.log(res.tempFiles)
          this.currentImages.unshift(...res.tempFiles);
          console.log(this.currentImages);
        }
      });
    },

    // 本地图片上传或拍照
    chooseImage(index: number) {
      const sourceTypes: Array<any> = ['camera', 'album'];
      uni.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'], // 照片压缩或原图
        success: (res) => {
          console.log(res.tempFiles)
          this.currentImages.unshift(...res.tempFiles)
          console.log("this.currentImages =-=-", this.currentImages);
        },
      });
    },

    // 转换照片
    rotateImage(direction: string) {
      uni.showLoading()
      const currentImage = this.currentImages[this.currentIndex];
      const degree = direction === 'left' ? -90 : 90;

      uni.getImageInfo({
        src: currentImage.tempFilePath || currentImage.path,
        success: (res) => {
          const width = res.width;
          const height = res.height;

          this.canvasWidth = degree % 180 === 0 ? width : height;
          this.canvasHeight = degree % 180 === 0 ? height : width;
          const {canvasHeight, canvasWidth} = this

          const ctx = uni.createCanvasContext('rotateCanvas', this);

          // clear canvas
          ctx.clearRect(0, 0, canvasWidth, canvasHeight);

          // 旋转 canvas
          ctx.translate(canvasWidth / 2, canvasHeight / 2);
          ctx.rotate(degree * Math.PI / 180);

          // create image
          ctx.drawImage(res.path, -width / 2, -height / 2, width, height);

          ctx.draw(false, () => {
            uni.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: canvasWidth,
              height: canvasHeight,
              destWidth: canvasWidth,
              destHeight: canvasHeight,
              quality: 1,
              canvasId: 'rotateCanvas',
              success: (tempRes) => {
                this.currentImages[this.currentIndex].tempFilePath = tempRes.tempFilePath;
              },
              complete: () => {
                uni.hideLoading();
              }
            });
          });
        }
      });
    },

    // 删除照片
    onCloseImage(index: number) {
      this.currentImages.splice(index, 1);
      // 当前 index 改变最前面的解决
      if (index >= this.currentImages.length) {
        this.currentIndex = this.currentImages.length - 1;
      }
    },

    // 编译照片
    async onEditImage() {
      const {currentImages, currentIndex: index} = this
      this.currentImages[index].tempFilePath = await editImageChange(currentImages[index].path || currentImages[index].tempFilePath);
    },

    // 轮播图刷新
    onSwiperChange({detail}) {
      this.currentIndex = detail.current; // 获取当前索引
    },

    // 选择纸
    onPaperTypeChange({detail}) {
      const paperSize = parseInt(detail.value)
      this.paperSize = paperSize
      // 避免 a4 纸打印错 (为了推荐 3:短边, 2:长边)
      this.duplex = paperSize === 8 ? 3 : 2
      this.calculatePrice();
    },

    // 选择打印数量
    onPrintCountChange({value}) {
      this.printCount = value
      this.calculatePrice();
    },
    // 双面
    onDoubleChange({detail}) {
      this.duplex = parseInt(detail.value);
      this.calculatePrice();
    },

    // 彩色打印点击
    onPrintColorChange({detail}) {
      this.printColor = parseInt(detail.value)
      this.calculatePrice();
    },

    // 打印方向 radio
    onOrientationChange({detail}) {
      const orientation = parseInt(detail.value)
      this.orientation = orientation
      // 避免 a4 纸打印错 (为了推荐 3:短边, 2:长边)
      if (this.paperSize === 9) {
        this.duplex = orientation === 1 ? 2 : 3
      }
      console.log("this.radioCurrent", this.radioCurrent)
    },

    // 缩放比例
    onSelectScaleChange(index: number) {
      this.scaleIndex = index;
      this.scalePopup = false
    },
    onSelectAutoAlign(index: number) {
      this.autoAlignIndex = index;
      this.autoAlignPopup = false
    },
    // 打印质量
    onQualityChange(index: number) {
      this.qualityIndex = index;
      this.qualityPopup = false
    },

    // 计算价格
    calculatePrice() {
      const {printCount, printColor, duplex, paperSize, printer, currentImages} = this;
      // Get prices based on paper type (A3/A4)
      const getPrices = (size: string) => {
        const prefix = size.toLowerCase();
        return {
          single: {
            black: parseFloat(printer[`${prefix}_image_black_white_price`]),
            color: parseFloat(printer[`${prefix}_image_color_price`])
          },
          double: {
            black: parseFloat(printer[`${prefix}_double_image_black_white_price`]),
            color: parseFloat(printer[`${prefix}_double_image_color_price`])
          }
        };
      };

      let totalPages = currentImages.length;

      // if (double) {
      //   totalPages = totalPages === 1 ? totalPages : Math.ceil(totalPages / 2);
      // }
      const totalCopies = totalPages * printCount;

      // 根据纸张类型(A3/A4)获取对应价格
      const prices = getPrices(parseInt(paperSize) === 9 ? 'a4' : 'a3');
      console.log("prices -=-=", prices)
      const unitPrice = prices[duplex >= 2 ? 'double' : 'single'][printColor === 2 ? 'color' : 'black'];
      console.log("unitPrice =--=", unitPrice)

      this.totalPrice = duplex >= 2 ? (totalCopies / 2) * unitPrice : totalCopies * unitPrice;

    },

    async servicesUploadImage() {
      return new Promise((resolve, reject) => {
        uni.showLoading({title: '加载中...'});

        const promises = this.currentImages.map((item: any) =>
            new Promise((resolve, reject) => {
              uni.uploadFile({
                url: uploadImageServer,
                name: 'file',
                filePath: item.path || item.tempFilePath,
                success: (res) => {
                  const resData = JSON.parse(res.data);
                  if (resData.code === 200) {
                    resolve(resData.data.url);
                  } else {
                    reject(new Error(`رەسىم يۈكلەش مەغلۇپ بولدى: ${resData.code}`));
                  }
                },
                fail: reject
              });
            })
        );

        Promise.all(promises).then((uploadedUrls) => {
          resolve(uploadedUrls);
          uni.hideLoading();
        }).catch((error) => {
          uni.hideLoading();
          reject(error);
        });
      });
    },

    async printImagePay() {
      console.log("printImagePay");
      // 检查盒子状态
      // if (!this.machineOnline) {
      //   tips.toast(this.otherLang.not_printer);
      //   this.$store.commit("setMachineOnline");
      //   return;
      // }
      try {
        console.log('this is printImagePay front')

        const imageUrls = await this.servicesUploadImage();
        console.log(imageUrls);

        console.log('this is printImagePay after')
        return;

        const {
          printCount, printColor, duplex, paperSize, orientation, selectedAutoAlign, autoAlignIndex,
          selectedScale, scaleIndex, qualities, qualityIndex, printer: {id, port, driver_name},
          machine: {device_id, device_password}
        } = this


        const printParams: any = {
          deviceId: device_id, //  盒子ID
          deviceKey: device_password, // 盒子密码
          devicePort: port, // 盒子端口
          printerModel: driver_name, // 打印机型号
          dmCopies: printCount, // 打印份数
          dmPaperSize: parseInt(paperSize), // 纸张类型
          isPreview: 0, // 预览
          dmDefaultSource: 7,
          jpAutoScale: 4, // 自动缩放
          jpAutoAlign: selectedAutoAlign[autoAlignIndex].label, // 自动对齐
          pdfKernel: 'mode1', // 文字增强
          jpScale: selectedScale[scaleIndex].label, // 缩放
          dmPrintQuality: qualities[qualityIndex].label,
          ext: getFileExtension(imageUrls[0]), // 打印文件扩展名
          page: imageUrls.length,// 页码
          jobFile: imageUrls.join('\n'), // 打印文件
          jpAutoRotate: 0, // 自动旋转
          reportDeviceStatus: 1, // 拦截设备状态异常任务
          reportPrinterStatus: 1, // 拦截打印机状态异常任务
          dmColor: printColor, // 打印颜色
          dmOrientation: orientation, // 打印方向
          dmDuplex: duplex, // 双面打印
        };

        uni.showLoading({title: '加载中...'});
        const result = await createOrder({
          printer_id: id, params: printParams, type: 'image', files: [printParams.jobFile]
        });

        console.log("准备支付=====", result);
        if (result.code === 200) {
          const {wechat_order, order_id} = result.data;
          await uni.requestPayment({
            ...wechat_order,
            success: async () => {
              tips.toast("支付成功")
              const tackIdRes = await getTaskId(order_id);
              const {code, data: {task_id}, msg} = tackIdRes;
              if (code === 200) {
                console.log("printFileFun-=--=-=-=- task_id", order_id, task_id)
                // 为了预览
                printParams.taskId = task_id
                await uni.navigateTo({
                  url: `/pages/print_loading/print_loading?params=${
                      encodeURIComponent(JSON.stringify({order_id, type: 2, print_params: printParams}))}`
                });
              } else {
                tips.toast(msg, 6000);
                console.log("printFileFun-=--=-=-=-", tackIdRes)
              }
            },
            fail: (err) => {
              console.log('支付失败:', err);
            },
          });
        } else {
          console.log('创建订单失败:', result);
          tips.toast(result.msg);
        }
      } catch (err) {
        console.error('创建订单失败:', err);
      } finally {
        uni.hideLoading();
      }
    }
  }
}
</script>

<style lang="scss" scoped>

.rotate-buttons {
  display: flex;
  gap: 20rpx;
  justify-content: center;
  margin-top: 20rpx;

  .rotate-btn {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    border-radius: 50%;

    &:active {
      background: #e0e0e0;
    }
  }
}

.image-card-box {
  height: 561rpx;

  .add-image-box {
    margin: 0 40rpx;
    position: relative;
    background: white;
    transition: all 0.3s ease;

    &.horizontal {
      height: 397rpx;
      width: 561rpx;

      .image-box {
        width: 460rpx;
      }
    }

    &:not(.horizontal) {
      height: 561rpx;
      width: 397rpx;
    }

    .image-box {
      width: 100%;
      height: 100%;
      display: flex;
      overflow: hidden;

      //height: 100%;
      //display: flex;
      //align-items: center;
      //justify-content: center;
      //overflow: hidden;
      transition: all 0.3s ease;

      .image {
        object-fit: contain;
        max-width: 100%;
        max-height: 100%;
      }

      .close-btn {
        position: absolute;
        top: -5rpx;
        right: -5rpx;
      }
    }
  }
}

.photo-count {
  padding: 10rpx 14rpx 10rpx 14rpx;
}

/** 操作按钮*/
.action-buttons {
  margin: 20rpx 0;

  .action-btn {
    flex: 1;
    gap: 10rpx;
    padding: 16rpx 18rpx;
    border-radius: 40rpx;
    color: #fff;

    &.edit {
      background: $uni-color-primary;
    }

    &.close {
      background: $uni-color-error;
    }

    &.add {
      border: 2rpx solid #2BE2A0;
      color: #2BE2A0;
    }
  }
}

.width-50 {
  width: 50%;
}

/** 打印设置*/
.print-settings {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  //margin-bottom: 120rpx;
  .setting-head {
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #eee;
  }

  .setting-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    radio-group {
      display: flex;
      gap: 20rpx;

      label {
        display: flex;
        align-items: center;
        gap: 8rpx;
      }
    }

    slider {
      flex: 1;
      margin: 0 20rpx;
    }
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 30rpx;
  font-size: 32rpx;
  font-weight: 500;
}

/** 对着*/
.position-popup {
  .position-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;

    .position-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 10rpx;
      padding: 20rpx;
      border-radius: 12rpx;

      .position-icon {
        width: 40rpx;
        height: 40rpx;
        border: 2rpx solid #999;
        border-radius: 8rpx;
      }

      text {
        font-size: 24rpx;
        color: #666;
      }

      &.active {
        background: #f0f0f0;

        .position-icon {
          border-color: $uni-color-primary;
          background: $uni-color-primary;
        }

        text {
          color: $uni-color-primary;
        }
      }
    }
  }
}

.popup-list {
  max-height: 400rpx;

  .popup-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;

    &.active {
      color: #07c160;
    }

    text {
      font-size: 28rpx;
    }
  }
}
</style>
